using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Text;
using System.ServiceModel;
using log4net;
using log4net.Config;
using Watchdog.Bll;
using Watchdog.Bll.Factory;
using Watchdog.Engines;

namespace Watchdog.Dispatcher.Console {
    class Program {
        static ServiceHost serverteamdatahost;
        static ServiceHost watchdogdatahost;
        static ServiceHost dispatcherhost;
        static ILog log = LogManager.GetLogger ("servicehost.Logging");

        //static ScheduleEngine scheduleengine;

        static void Main ( string[] args ) {
            // Cleanup


            //log = log4net.LogManager.GetLogger ("servicehost.Logging");
            //scheduleengine = new ScheduleEngine ();
            Start ();
            bool ok = false;
            while (!ok) {
                System.Threading.Thread.Sleep (10);
            }
            System.Console.ReadLine ();
            Stop ();
            System.Threading.Thread.Sleep (1000);
        }

        public static void Start () {
            //log.Info ("start");
            // Step 1 : Start the Wcf Dataservices
            Log.Write (Severity.Info, "Starting Wcf Service Hosts");
            serverteamdatahost = new ServiceHost (typeof (ServerTeam.Wcf.ServerTeamDataService));
            watchdogdatahost = new ServiceHost (typeof (Watchdog.Wcf.WatchdogDataService));
            dispatcherhost = new ServiceHost (typeof (Watchdog.DispatcherService));
            serverteamdatahost.Open ();
            watchdogdatahost.Open ();
            dispatcherhost.Open ();
            // Step 2 : cleanup state from previous session
            // unlock lock locked shedules
            Log.Write (Severity.Info, "Unlocking previous locked schedules");
            List<Schedule> locked = ScheduleFactory.GetLocked ();
            foreach (Schedule sched in locked) {
                sched.Unlock ();
                Log.Write (Severity.Info, "Schedule : " + sched.Id.ToString () + " unlocked.");
            }
            Log.Write (Severity.Info, "Starting Schedule Engine");
            Context.Current.ScheduleEngine.Start ();
        }
        public static void Stop () {
            // Step 1 : Stop the Wcf Dataservices
            serverteamdatahost.Close ();
            serverteamdatahost = null;
            watchdogdatahost.Close ();
            watchdogdatahost = null;
            dispatcherhost.Close ();
            dispatcherhost = null;
            //log.Debug ("service stopped");
            Context.Current.ScheduleEngine.Stop ();
        }
    }
}
